package com.qcxk.yuqian.rtu.controller;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.qcxk.yuqian.rtu.controller.model.page.Pagination;
import com.qcxk.yuqian.rtu.controller.model.query.RtuDTO;
import com.qcxk.yuqian.rtu.controller.model.query.RtuDataDTO;
import com.qcxk.yuqian.rtu.controller.model.query.RtuSetDTO;
import com.qcxk.yuqian.rtu.controller.model.query.RtuVO;
import com.qcxk.yuqian.rtu.controller.model.response.PageResponse;
import com.qcxk.yuqian.rtu.controller.model.response.Response;
import com.qcxk.yuqian.rtu.entity.Rtu;
import com.qcxk.yuqian.rtu.entity.RtuMeter;
import com.qcxk.yuqian.rtu.entity.RtuSet;
import com.qcxk.yuqian.rtu.entity.RtuSetHis;
import com.qcxk.yuqian.rtu.service.IRtuMeterService;
import com.qcxk.yuqian.rtu.service.IRtuService;
import com.qcxk.yuqian.rtu.service.IRtuSetHisService;
import com.qcxk.yuqian.rtu.service.IRtuSetService;
import com.qcxk.yuqian.system.utils.DataUtils;
import com.qcxk.yuqian.system.utils.RedisUtil;
import com.qcxk.yuqian.system.utils.ThmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.SystemException;
import org.springframework.web.bind.annotation.RequestMapping;
import com.qcxk.yuqian.system.component.behaviour.BehaviourOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qcxk.yuqian.system.component.constant.SystemConstant;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @auther lp
 * @create 2021-11-15 03:21:45
 * @describe 前端控制器
 */
@Slf4j
@RestController
@RequestMapping("/rtu")
public class RtuController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IRtuService rtuService;
    @Autowired
    private IRtuMeterService rtuMeterService;
    @Autowired
    private IRtuSetService rtuSetService;
    @Autowired
    private IRtuSetHisService rtuSetHisService;


    @BehaviourOperator(desc = "查询Rtu流量计信息")
    @RequestMapping(value = "/loadRtuMeter")
    public Response loadRtuMeter(String id) {
        List<Map<String, String>> m = rtuMeterService.findRtuMeter(Long.valueOf(id));
        return Response.build(m).success();
    }
    @BehaviourOperator(desc = "查询Rtu地址信息")
    @RequestMapping(value = "/findRtuAddress")
    public Response findRtuAddress(String ad) {
        Rtu rtu=new Rtu();
        rtu.setAreaId(ad);
        List<RtuDTO> l = rtuService.getRtuAddress(rtu);

        return Response.build(l).success();
    }

    @BehaviourOperator(desc = "查询Rtu流量计信息")
    @RequestMapping(value = "/loadRtuMeterById")
    public Response loadRtuMeterById(String id) {
        Map<String, String> m = rtuMeterService.findRtuMeterById(Long.valueOf(id));
        return Response.build(m).success();
    }
    @BehaviourOperator(desc = "查询Rtu流量计信息")
    @RequestMapping(value = "/loadListRtuMeterById")
    public Response loadListRtuMeterById(String id) {
        List<Map<String, String>> m = rtuMeterService.findListRtuMeterById(Long.valueOf(id));
        return Response.build(m).success();
    }
    @BehaviourOperator(desc = "查询Rtu信息")
    @RequestMapping(value = "/loadRtu")
    public Response loadRtu(Long id) {

        Rtu m = rtuService.findRtuById(id);
        if(m.getStatus()==1||m.getStatus()==3||m.getStatus()==4){
            m.setStatus(1);
        }
        return Response.build(m).success();
    }

/*    @BehaviourOperator(desc = "查询Rtu列表")
    @RequestMapping(value = "/queryRtuStatusList")
    public JSONObject queryRtuStatusList(Page page, Rtu rtu) {
        JSONObject json = new JSONObject();
        page = rtuService.queryRtuPage(page, rtu);
        json.put("code", "0");
        json.put("current", page.getCurrent());
        json.put("size", page.getSize());
        json.put("total", page.getTotal());

        List<HashMap> list = page.getRecords();

        JSONArray jsonArray = new JSONArray();
        for (int k = 0; k < list.size(); k++) {
            HashMap e = list.get(k);
            JSONObject item = (JSONObject) JSONObject.toJSON(e);
      *//*      if (item.containsKey("data_body") && item.getString("data_body") != null) {
                for (int i = 0; i < item.getString("data_body").length() / 8; i++) {
                    String numtext = item.getString("data_body").substring(i * 8, (i + 1) * 8);
                    item.put("channel" + (i + 1), DataUtils.decodeHEX(numtext));
                }
            }*//*
            jsonArray.add(item);
        }

        json.put("dataList", jsonArray);
        return json;
    }*/
    @BehaviourOperator(desc = "查询Rtu列表")
    @RequestMapping(value = "/queryRtuStatusList")
    public Response queryRtuStatusList(RtuVO dto) {

        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<RtuVO> list = rtuService.findRTUList(dto);
        Pagination pagination = Pagination.buildPagination(list, dto);

        return PageResponse.pageResponse(pagination, list).success();
    }

    @BehaviourOperator(desc = "查询Rtu列表")
    @RequestMapping(value = "/queryRtuStatusList1")
    public JSONObject queryRtuStatusList1(Page page, Rtu rtu) {
        JSONObject json = new JSONObject();
        page = rtuService.queryRtuStatusPage(page, rtu);
        json.put("code", "0");
        json.put("current", page.getCurrent());
        json.put("size", page.getSize());
        json.put("total", page.getTotal());

        List<HashMap> list = page.getRecords();

        JSONArray jsonArray = new JSONArray();
        for (int k = 0; k < list.size(); k++) {
            HashMap e = list.get(k);
            JSONObject item = (JSONObject) JSONObject.toJSON(e);
      /*      if (item.containsKey("data_body") && item.getString("data_body") != null) {
                for (int i = 0; i < item.getString("data_body").length() / 8; i++) {
                    String numtext = item.getString("data_body").substring(i * 8, (i + 1) * 8);
                    item.put("channel" + (i + 1), DataUtils.decodeHEX(numtext));
                }
            }*/
            jsonArray.add(item);
        }

        json.put("dataList", jsonArray);
        return json;
    }

    @BehaviourOperator(desc = "单一属性修改Rtu")
    @RequestMapping(value = "/updateRtuSingle")
    public JSONObject updateRtuSingle(Integer id, String column, String value) throws NoSuchFieldException, IllegalAccessException {
        JSONObject json = new JSONObject();
        Rtu rtu = rtuService.getById(id);
        Class<? extends Rtu> clazz = rtu.getClass();// 获取到对象对应的class对象
        Field nameField = clazz.getDeclaredField(column);// 获取私有成员变量:column
        nameField.setAccessible(true);// 设置操作权限为true
        nameField.set(rtu, value);
        if (rtuService.updateById(rtu)) {
            json.put("code", "0");
        } else {
            json.put("code", "1");
            json.put("msg", SystemConstant.SYS_DATABASE_ERROR_CN);
        }
        return json;
    }

    @BehaviourOperator(desc = "整体修改Rtu")
    @RequestMapping(value = "/updateRtuMultiple")
    public Response updateRtuMultiple(RtuDTO dto) {
        try {
            Rtu rtuOld = rtuService.getById(dto.getRtuId());
            if(rtuOld==null){
                Rtu rtu = new Rtu();
                rtu.setRtuNo(dto.getRtuNo());
                rtu.setRtuType(dto.getRtuType());
                rtu.setRtuName(dto.getRtuName());
                rtu.setStatus(0);//默认离线
                rtu.setDeleted(0);//默认
                rtu.setCtime(getDate());
                rtu.setUpdateTime(getDate());
                rtu.setAreaId(dto.getAreaId());
                rtu.setFlag("0");
                rtu.setRemark(dto.getRemark());
                rtuService.addRtu(rtu);
   /*             List<RtuMeter> rtuMeterList = new ArrayList<>();
                if (dto.getItem() != null) {
                    for (Map<String, String> m : dto.getItem()
                    ) {
                        if ("1".equals(m.get("status"))) {
                            RtuMeter rm1 = new RtuMeter();
                            Map s = rtuMeterService.findRtuMeterByIdAndMeterCode(rtu.getId(), m.get("meterCode"));
                            if (s != null) {
                                log.info("编号已存在", s);
                            } else {
                                rm1.setRtuId(rtu.getId());
                                rm1.setMeterCode(m.get("meterCode"));
                                rm1.setMeterModel(m.get("meterModel"));
                                rm1.setMeterName(m.get("meterName"));
                                rm1.setCreateTime(getDate());
                                rm1.setUpdateTime(getDate());
                                rm1.setVendorId(m.get("vendorId"));
                                rm1.setVendorName(m.get("vendorName"));
                                rm1.setPipelineId(m.get("pipelineId"));
                                rm1.setPipelineName(m.get("pipelineName"));
                                rm1.setStationId(m.get("stationId"));
                                rm1.setStationName(m.get("stationName"));
                                rm1.setDisCustomerId(m.get("disCustomerId"));
                                rm1.setDisCustomerName(m.get("disCustomerName"));
                                rm1.setCustomerId(m.get("customerId"));
                                rm1.setCustomerName(m.get("customerName"));
                                rtuMeterList.add(rm1);
                            }
                        }
                    }
                }
                rtuMeterService.batchAddRtuMeter(rtuMeterList);*/
                return Response.build().success();
            }else {
                Rtu rtu = rtuService.findRtu(dto.getRtuNo());
                if (rtu != null) {
                    if (rtu.getId().equals(rtuOld.getId())) {
                        rtuOld.setRtuNo(dto.getRtuNo());
                        rtuOld.setUpdateTime(getDate());
                        rtuOld.setRtuName(dto.getRtuName());
                        rtuOld.setAreaId(dto.getAreaId());
                        rtuOld.setId(dto.getRtuId());
                        rtuOld.setRemark(dto.getRemark());
                        rtuOld.setOrganId(dto.getOrganId());
                        if(dto.getFlag()!=null){
                            rtuOld.setFlag(dto.getFlag().toString());
                        }
                        if(rtu.getMasterIp()!=null){
                            if(!rtu.getMasterIp().equals(dto.getMasterIp())){
                                rtuOld.setFlag("3");
                            }
                        }
                        if(rtu.getMasterPort()!=null){
                            if(!rtu.getMasterPort().equals(dto.getMasterPort())){
                                rtuOld.setFlag("3");
                            }
                        }
                        if(rtu.getSecondaryIp()!=null){
                            if(!rtu.getSecondaryIp().equals(dto.getSecondaryIp())){
                                rtuOld.setFlag("3");
                            }
                        }
                        if(rtu.getSecondaryPort()!=null){
                            if(!rtu.getSecondaryPort().equals(dto.getSecondaryPort())){
                                rtuOld.setFlag("3");
                            }
                        }

                     /*   if(!rtu.getMasterIp().equals(dto.getMasterIp())||!rtu.getMasterPort().equals(dto.getMasterPort())||!rtu.getSecondaryIp().equals(dto.getSecondaryIp())||!rtu.getSecondaryPort().equals(dto.getSecondaryPort())){
                            rtuOld.setFlag("3");
                        }*/
                        rtuOld.setMasterIp(dto.getMasterIp());
                        rtuOld.setMasterPort(dto.getMasterPort());
                        rtuOld.setSecondaryIp(dto.getSecondaryIp());
                        rtuOld.setSecondaryPort(dto.getSecondaryPort());

                        rtuOld.setHeartTime(dto.getHeartTime());
                        rtuOld.setUploadTime(dto.getUploadTime());
                     //   rtuOld.setSecret(dto.getSecret());
                        rtuOld.setSecret("974F5C7F19D8FAA5B2095B3438818890");
                        rtuOld.setSysTime(dto.getSysTime());

                        if(dto.getTransferMode()!=null){
                            rtuOld.setTransferMode(dto.getTransferMode().toString());
                        }
                        if(dto.getSwitch1()!=null){
                            rtuOld.setSwitch1(dto.getSwitch1().toString());
                        }
                        if(dto.getSwitch2()!=null){
                            rtuOld.setSwitch2(dto.getSwitch2().toString());
                        }
                        if(dto.getSwitch3()!=null){
                            rtuOld.setSwitch3(dto.getSwitch3().toString());
                        }
                        if(dto.getSwitch4()!=null){
                            rtuOld.setSwitch4(dto.getSwitch4().toString());
                        }
                        rtuOld.setDeleted(dto.getDeleted());
                        rtuService.updateById(rtuOld);
                    } else {
                        return Response.build().fail("RTU设备编号已存在");
                    }
                } else {
                    rtuOld.setRtuNo(dto.getRtuNo());
                    rtuOld.setUpdateTime(getDate());
                    rtuOld.setRtuName(dto.getRtuName());
                    rtuOld.setAreaId(dto.getAreaId());
                    rtuOld.setId(dto.getRtuId());
                    rtuOld.setMasterIp(dto.getMasterIp());
                    rtuOld.setMasterPort(dto.getMasterPort());
                    rtuOld.setSecondaryIp(dto.getSecondaryIp());
                    rtuOld.setSecondaryPort(dto.getSecondaryPort());
                    rtuOld.setHeartTime(dto.getHeartTime());
                    rtuOld.setUploadTime(dto.getUploadTime());
                   // rtuOld.setSecret(dto.getSecret());
                    rtuOld.setSecret("974F5C7F19D8FAA5B2095B3438818890");
                    rtuOld.setSysTime(dto.getSysTime());
                    rtuOld.setFlag("3");
                    rtuOld.setRemark(dto.getRemark());
                    rtuOld.setOrganId(dto.getOrganId());
                    if(dto.getTransferMode()!=null){
                        rtuOld.setTransferMode(dto.getTransferMode().toString());
                    }
                    if(dto.getSwitch1()!=null){
                        rtuOld.setSwitch1(dto.getSwitch1().toString());
                    }
                    if(dto.getSwitch2()!=null){
                        rtuOld.setSwitch2(dto.getSwitch2().toString());
                    }
                    if(dto.getSwitch3()!=null){
                        rtuOld.setSwitch3(dto.getSwitch3().toString());
                    }
                    if(dto.getSwitch4()!=null){
                        rtuOld.setSwitch4(dto.getSwitch4().toString());
                    }
                    rtuOld.setDeleted(dto.getDeleted());
                    rtuService.updateById(rtuOld);
                }
                return Response.build().success();
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Response.build().fail(SystemConstant.SYS_EXCEPTION_CN);
        }
    }

    @RequestMapping(value = "/deleteRtuMultiple")
    public Response deleteRtuMultiple(RtuDTO dto) {
        try {
            Rtu rtuOld = rtuService.getById(dto.getRtuId());
            if(dto.getDeleted()==2){
                rtuService.deleteById(rtuOld);
            }else {
                rtuOld.setUpdateTime(getDate());
                rtuOld.setDeleted(dto.getDeleted());
                rtuService.updateById(rtuOld);
            }
            return Response.build().success();
        } catch (Exception e) {
            e.printStackTrace();
            return Response.build().fail(SystemConstant.SYS_EXCEPTION_CN);
        }
    }
    @RequestMapping(value = "/deleteRtuMeterMultiple")
    public Response deleteRtuMeterMultiple(RtuDTO dto) {
        try {
            RtuMeter rtuOld = rtuMeterService.getById(dto.getRtuMeterId());
            rtuOld.setUpdateTime(getDate());
            rtuOld.setDeleted(dto.getDeleted());
            rtuMeterService.updateById(rtuOld);
            return Response.build().success();
        } catch (Exception e) {
            e.printStackTrace();
            return Response.build().fail(SystemConstant.SYS_EXCEPTION_CN);
        }
    }
    @BehaviourOperator(desc = "增加RtuMeter")
    @RequestMapping(value = "/addRtuMeter")
    public Response addRtuMeter(RtuDTO dto) {
        try {
            Map s = rtuMeterService.findRtuMeterByRtuIdAndMeterCode(dto.getRtuId(), dto.getMeterCode());
            if (s != null && !s.get("id").equals(dto.getRtuMeterId())) {
                return Response.build().fail("流量计编号重复");
            } else {
                RtuMeter rm = new RtuMeter();
                rm.setMeterCode(dto.getMeterCode());
                rm.setMeterNum(dto.getMeterNum());
                rm.setMeterModel(dto.getMeterModel());
                rm.setMeterName(dto.getMeterName());
                rm.setUpdateTime(getDate());
                rm.setVendorId(dto.getVendorId());
                rm.setVendorName(dto.getVendorName());
                rm.setPipelineId(dto.getPipelineId());
                rm.setPipelineName(dto.getPipelineName());
                rm.setStationId(dto.getStationId());
                rm.setStationName(dto.getStationName());
                rm.setDisCustomerId(dto.getDisCustomerId());
                rm.setDisCustomerName(dto.getDisCustomerName());
                rm.setCustomerId(dto.getCustomerId());
                rm.setCustomerName(dto.getCustomerName());
                rm.setId(dto.getRtuMeterId());
                rm.setRtuId(dto.getRtuId());
                if (dto.getRtuMeterId() == null || "".equals(dto.getRtuMeterId())) {
                    rtuMeterService.addRtuMeter(rm);
                } else {
                    rtuMeterService.updateById(rm);
                }
                return Response.build().success();
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Response.build().fail(SystemConstant.SYS_EXCEPTION_CN);
        }
    }

    @BehaviourOperator(desc = "删除Rtu")
    @RequestMapping(value = "/deleteRtuById")
    public JSONObject deleteRtuById(Rtu rtu) {
        JSONObject json = new JSONObject();
        if (rtuService.deleteById(rtu)) {
            json.put("code", "0");
        } else {
            json.put("code", "1");
            json.put("msg", SystemConstant.SYS_DATABASE_ERROR_CN);
        }
        return json;
    }

    @BehaviourOperator(desc = "新增Rtu")
    @RequestMapping(value = "/addRtu")
    public Response addRtu(RtuDTO dto) {

        Rtu rtuOld = rtuService.findRtu(dto.getRtuNo());
        if (rtuOld == null) {
            Rtu rtu = new Rtu();
            rtu.setRtuNo(dto.getRtuNo());
            rtu.setRtuType(dto.getRtuType());
            rtu.setRtuName(dto.getRtuName());
            rtu.setStatus(0);//默认离线
            rtu.setDeleted(0);//默认
            rtu.setCtime(getDate());
            rtu.setUpdateTime(getDate());
            rtu.setAreaId(dto.getAreaId());
            rtu.setFlag("0");
           // rtu.setSecret(dto.getSecret());
            if("3".equals(dto.getRtuType())){
                rtu.setSecret("974F5C7F19D8FAA5B2095B3438818890");
            }
            rtu.setMasterIp(dto.getMasterIp());
            rtu.setMasterPort(dto.getMasterPort());
            rtu.setSecondaryIp(dto.getSecondaryIp());
            rtu.setSecondaryPort(dto.getSecondaryPort());
            rtu.setHeartTime(dto.getHeartTime());
            rtu.setTransferMode(dto.getTransferMode()==null?"0":dto.getTransferMode().toString());
            rtu.setUploadTime(dto.getUploadTime());
            rtu.setSwitch1(dto.getSwitch1()==null?"0":dto.getSwitch1().toString());
            rtu.setSwitch2(dto.getSwitch2()==null?"0":dto.getSwitch2().toString());
            rtu.setSwitch3(dto.getSwitch3()==null?"0":dto.getSwitch3().toString());
            rtu.setSwitch4(dto.getSwitch4()==null?"0":dto.getSwitch4().toString());
            rtu.setSource(dto.getSource());
            rtu.setOrganId(dto.getOrganId());
            rtu.setRemark(dto.getRemark());
            rtuService.addRtu(rtu);
            List<RtuMeter> rtuMeterList = new ArrayList<>();
            if (dto.getItem() != null) {
                for (Map<String, String> m : dto.getItem()
                ) {
                    if ("1".equals(m.get("status"))) {
                        RtuMeter rm1 = new RtuMeter();
                        Map s = rtuMeterService.findRtuMeterByIdAndMeterCode(rtu.getId(), m.get("meterCode"));
                        if (s != null) {
                            log.info("编号已存在", s);
                        } else {
                            rm1.setRtuId(rtu.getId());
                            rm1.setMeterCode(m.get("meterCode"));
                            rm1.setMeterModel(m.get("meterModel"));
                            rm1.setMeterName(m.get("meterName"));
                            rm1.setCreateTime(getDate());
                            rm1.setUpdateTime(getDate());
                            rm1.setVendorId(m.get("vendorId"));
                            rm1.setVendorName(m.get("vendorName"));
                            rm1.setPipelineId(m.get("pipelineId"));
                            rm1.setPipelineName(m.get("pipelineName"));
                            rm1.setStationId(m.get("stationId"));
                            rm1.setStationName(m.get("stationName"));
                            rm1.setDisCustomerId(m.get("disCustomerId"));
                            rm1.setDisCustomerName(m.get("disCustomerName"));
                            rm1.setCustomerId(m.get("customerId"));
                            rm1.setCustomerName(m.get("customerName"));
                            rtuMeterList.add(rm1);
                        }
                    }
                }
                rtuMeterService.batchAddRtuMeter(rtuMeterList);
            }
            return Response.build().success();
        } else {
            return Response.build().fail(SystemConstant.SYS_RTU_ERROR_CN);
        }

    }

    @RequestMapping(value = "/queryRtuSetList")
    public Response queryRtuSetList(RtuSetDTO dto) {

        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<RtuSetDTO> list = rtuSetService.findDataList(dto);
        Pagination pagination = Pagination.buildPagination(list, dto);

        return PageResponse.pageResponse(pagination, list).success();
    }

    @RequestMapping(value = "/saveRtuSet")
    public Response saveRtuSet(RtuSetDTO dto) {

        Response r = rtuSetService.sendSettingMes(dto);
        RtuSet rs = new RtuSet();
        rs.setId(dto.getId());
        rs.setIp(dto.getOip() + ":" + dto.getPort());
        rs.setIp2(dto.getOip2() + ":" + dto.getPort2());
        if (r.getStatus() == 200) {
            rs.setStatus(1);
        } else {
            rs.setStatus(2);
        }
        rs.setUpdateTime(getDate());
        rs.setUploadTimer(dto.getUploadTimer());
        rs.setSwitch1(dto.getSwitch1());
        rs.setSwitch2(dto.getSwitch2());
        rs.setSwitch3(dto.getSwitch3());
        rs.setSwitch4(dto.getSwitch4());
        Boolean flag = rtuSetService.updateById(rs);
        if (flag) {
            RtuSetHis rsh = new RtuSetHis();
            rsh.setRtuSetId(dto.getId());
            rsh.setIp(dto.getOip() + ":" + dto.getPort());
            rsh.setIp2(dto.getOip2() + ":" + dto.getPort2());
            rsh.setStatus(rs.getStatus());
            rsh.setCreateTime(getDate());
            rsh.setUploadTimer(dto.getUploadTimer());
            rsh.setSwitch1(dto.getSwitch1());
            rsh.setSwitch2(dto.getSwitch2());
            rsh.setSwitch3(dto.getSwitch3());
            rsh.setSwitch4(dto.getSwitch4());
            rtuSetHisService.save(rsh);
            if (r.getStatus() == 200) {
                return Response.build().success(r.getMessage());
            } else {
                return Response.build().fail(r.getMessage());
            }
        } else {
            return Response.build().success("系统异常");
        }

    }

    public static String getDate() {
        SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
        sdf.applyPattern("yyyy-MM-dd HH:mm:ss");// a为am/pm的标记
        java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
        return sdf.format(date);
    }
}

